/*
 * Copyright (c) 2003-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Date: Nov. 2009
 * Author: Gou Pengfei
 */

#ifndef __EDGECPU_STATIC_INST_HH__
#define __EDGECPU_STATIC_INST_HH__

#include <bitset>
#include <string>

#include "cpu/static_inst.hh"

class EDGEAddrDecodePage;

namespace Trace {
    class EdgeInstRecord;
}
/**
 *
 * Author: Gou Pengfei
 * Date: Dec. 2009
 *
 * EDGE Static Inst class
 * This will only hold ISA related infos like operation class, target id, lsid,
 * and any infos encoded in ISA.
 * Any thing related to the operation of this instruction will be put into
 * EdgeDynInst class like operands and the interpretation of target id.
 */
class EDGEStaticInst : public StaticInstBase
{
  public:

    /// Binary machine instruction type.
    typedef TheISA::MachInst MachInst;
    /// Binary extended machine instruction type.
    typedef TheISA::ExtMachInst ExtMachInst;
    /// RegIndex
    typedef TheISA::RegIndex RegIndex;

    /// Consumer ID type
    typedef TheISA::ConsumerID ConsumerID;
    /// LSID type
    typedef TheISA::LsID LsID;
    /// EXIT type
    typedef TheISA::ExitID ExitID;
    typedef TheISA::Predication Predication;

    /// Max number of consumers and operands for one edge inst.
    enum  {
        MaxInstConsumers = TheISA::MaxInstConsumers,
        MaxInstOperands = TheISA::MaxInstOperands,
        MaxInstSrcRegs = TheISA::MaxInstSrcRegs,
        MaxInstDestRegs = TheISA::MaxInstDestRegs
    };

    /// Return logical index (architectural reg num) of i'th destination reg.
    /// Only the entries from 0 through numDestRegs()-1 are valid.
    RegIndex destRegIdx(int i) const { return _destRegIdx[i]; }

    /// Return logical index (architectural reg num) of i'th source reg.
    /// Only the entries from 0 through numSrcRegs()-1 are valid.
    RegIndex srcRegIdx(int i)  const { return _srcRegIdx[i]; }

    ///Return the num of consumers of this instruction
    uint32_t getNumConsumers() const{ return _numConsumers; }

    uint32_t getNumOperands() const { return _numOperands; }

    /// Return the ID of a consumer of this instruction
    ConsumerID getRawConsumerID(int i) const { return _consumerID[i]; }
    /// Return LSID only when this is memory refenrence instruction
    LsID getLSID() const { assert(isMemRef()); return _lsID;}
    /// Return EXIT ID only when this is PC-control instruction
    ExitID getEXIT() const { assert(isControl()); return _exitID;}
    Predication getPredication() const { return _predication; }

    /// Pointer to a statically allocated "null" instruction object.
    /// Used to give eaCompInst() and memAccInst() something to return
    /// when called on non-memory instructions.
    static EDGEStaticInstPtr nullEDGEStaticInstPtr;

    /**
     * Memory references only: returns "fake" instruction representing
     * the effective address part of the memory operation.  Used to
     * obtain the dependence info (numSrcRegs and srcRegIdx[]) for
     * just the EA computation.
     */
    virtual const
    EDGEStaticInstPtr &eaCompInst() const { return nullEDGEStaticInstPtr; }

    /**
     * Memory references only: returns "fake" instruction representing
     * the memory access part of the memory operation.  Used to
     * obtain the dependence info (numSrcRegs and srcRegIdx[]) for
     * just the memory access (not the EA computation).
     */
    virtual const
    EDGEStaticInstPtr &memAccInst() const { return nullEDGEStaticInstPtr; }

    /// The binary machine instruction.
    const ExtMachInst machInst;

  protected:

    /// LSID for L/S instructions
    LsID _lsID;
    /// Exit ID for branch instructions
    ExitID _exitID;
    /// Predication indicator
    Predication _predication;
    /// Number of consumers of this instruction
    uint32_t _numConsumers;
    /// Number of operands of this instruction
    uint32_t _numOperands;

    /// See consumerID()
    ConsumerID _consumerID[MaxInstConsumers];

    /// See destRegIdx().
    RegIndex _destRegIdx[MaxInstDestRegs];
    /// See srcRegIdx().
    RegIndex _srcRegIdx[MaxInstSrcRegs];

    /**
     * Base mnemonic (e.g., "add").  Used by generateDisassembly()
     * methods.  Also useful to readily identify instructions from
     * within the debugger when #cachedDisassembly has not been
     * initialized.
     */
    const char *mnemonic;

    /**
     * String representation of disassembly (lazily evaluated via
     * disassemble()).
     */
    mutable std::string *cachedDisassembly;

    /**
     * Internal function to generate disassembly string.
     */
    virtual std::string
    generateDisassembly(Addr pc, const SymbolTable *symtab) const = 0;

    /// Constructor.
    EDGEStaticInst(const char *_mnemonic, ExtMachInst _machInst, OpClass __opClass)
        : StaticInstBase(__opClass),
          machInst(_machInst), mnemonic(_mnemonic), cachedDisassembly(0)
    { }

  public:
    virtual ~EDGEStaticInst();

/**
 * The execute() signatures are auto-generated by scons based on the
 * set of EDGECPU models we are compiling in today.
 */
#include "cpu/static_inst_exec_sigs.hh"

    /**
     * Return the target address for a PC-relative branch.
     * Invalid if not a PC-relative branch (i.e. isDirectCtrl()
     * should be true).
     */
    virtual Addr branchTarget(Addr branchPC) const;

    /**
     * Return the target address for an indirect branch (jump).  The
     * register value is read from the supplied thread context, so
     * the result is valid only if the thread context is about to
     * execute the branch in question.  Invalid if not an indirect
     * branch (i.e. isIndirectCtrl() should be true).
     */
    virtual Addr branchTarget(ThreadContext *tc) const;

    /**
     * Return true if the instruction is a control transfer, and if so,
     * return the target address as well.
     */
    bool hasBranchTarget(Addr pc, ThreadContext *tc, Addr &tgt) const;

    /**
     * Return string representation of disassembled instruction.
     * The default version of this function will call the internal
     * virtual generateDisassembly() function to get the string,
     * then cache it in #cachedDisassembly.  If the disassembly
     * should not be cached, this function should be overridden directly.
     */
    virtual const std::string &disassemble(Addr pc,
        const SymbolTable *symtab = 0) const;

    /// Decoded instruction cache type.
    /// For now we're using a generic hash_map; this seems to work
    /// pretty well.
    typedef m5::hash_map<ExtMachInst, EDGEStaticInstPtr> DecodeCache;

    /// A cache of decoded instruction objects.
    static DecodeCache decodeCache;

    /**
     * Dump some basic stats on the decode cache hash map.
     * Only gets called if DECODE_CACHE_HASH_STATS is defined.
     */
    static void dumpDecodeCacheStats();

    /// Decode a machine instruction.
    /// @param mach_inst The binary instruction to decode.
    /// @retval A pointer to the corresponding StaticInst object.
    //This is defined as inlined below.
    static EDGEStaticInstPtr decode(ExtMachInst mach_inst, Addr addr,
                                                                                                                   TheISA::BlockStatus blockstatus);

    /// Return name of machine instruction
    std::string getName() { return mnemonic; }

    /// Decoded instruction cache type, for address decoding.
    /// A generic hash_map is used.
    typedef m5::hash_map<Addr, EDGEAddrDecodePage *> AddrDecodeCache;

    /// A cache of decoded instruction objects from addresses.
    static AddrDecodeCache addrDecodeCache;

    struct cacheElement
    {
        Addr page_addr;
        EDGEAddrDecodePage *decodePage;

        cacheElement() : decodePage(NULL) { }
    };

    /// An array of recently decoded instructions.
    // might not use an array if there is only two elements
    static struct cacheElement recentDecodes[2];

    /// Updates the recently decoded instructions entries
    /// @param page_addr The page address recently used.
    /// @param decodePage Pointer to decoding page containing the decoded
    ///                   instruction.
    static inline void
    updateCache(Addr page_addr, EDGEAddrDecodePage *decodePage)
    {
        recentDecodes[1].page_addr = recentDecodes[0].page_addr;
        recentDecodes[1].decodePage = recentDecodes[0].decodePage;
        recentDecodes[0].page_addr = page_addr;
        recentDecodes[0].decodePage = decodePage;
    }

    /// Searches the decoded instruction cache for instruction decoding.
    /// If it is not found, then we decode the instruction.
    /// Otherwise, we get the instruction from the cache and move it into
    /// the address-to-instruction decoding page.
    /// @param mach_inst The binary instruction to decode.
    /// @param addr The address that contained the binary instruction.
    /// @param decodePage Pointer to decoding page containing the instruction.
    /// @retval A pointer to the corresponding StaticInst object.
    //This is defined as inlined below.
    static EDGEStaticInstPtr searchCache(ExtMachInst mach_inst, Addr addr,
                                     EDGEAddrDecodePage *decodePage, TheISA::BlockStatus blockstatus);
};


/// Reference-counted pointer to a StaticInst object.
/// This type should be used instead of "StaticInst *" so that
/// StaticInst objects can be properly reference-counted.
class EDGEStaticInstPtr : public RefCountingPtr<EDGEStaticInst>
{
  public:
    /// Constructor.
    EDGEStaticInstPtr()
        : RefCountingPtr<EDGEStaticInst>()
    {
    }

    /// Conversion from "StaticInst *".
    EDGEStaticInstPtr(EDGEStaticInst *p)
        : RefCountingPtr<EDGEStaticInst>(p)
    {
    }

    /// Copy constructor.
    EDGEStaticInstPtr(const EDGEStaticInstPtr &r)
        : RefCountingPtr<EDGEStaticInst>(r)
    {
    }

    /// Construct directly from machine instruction.
    /// Calls StaticInst::decode().
    explicit EDGEStaticInstPtr(TheISA::ExtMachInst mach_inst, Addr addr, TheISA::BlockStatus blockstatus)
        : RefCountingPtr<EDGEStaticInst>(EDGEStaticInst::decode(mach_inst, addr, blockstatus))
    {
    }

    /// Convert to pointer to StaticInstBase class.
    operator const StaticInstBasePtr()
    {
        return this->get();
    }
};

/// A page of a list of decoded instructions from an address.
class EDGEAddrDecodePage
{
  typedef TheISA::ExtMachInst ExtMachInst;
  protected:
    EDGEStaticInstPtr instructions[TheISA::PageBytes];
    bool valid[TheISA::PageBytes];
    Addr lowerMask;

  public:
    /// Constructor
    EDGEAddrDecodePage()
    {
        lowerMask = TheISA::PageBytes - 1;
        memset(valid, 0, TheISA::PageBytes);
    }

    /// Checks if the instruction is already decoded and the machine
    /// instruction in the cache matches the current machine instruction
    /// related to the address
    /// @param mach_inst The binary instruction to check
    /// @param addr The address containing the instruction
    /// @param blockstatus The block status of EDGE architecture.
    bool
    decoded(ExtMachInst mach_inst, Addr addr, TheISA::BlockStatus blockstatus)
    {
        bool status_valid;
        // Check if this inst is match for the block status.
        status_valid = valid[addr & lowerMask] &&
                       ((instructions[addr & lowerMask]->isGRegWR() &&
                       (blockstatus == TheISA::Head)) ||
                       (!instructions[addr & lowerMask]->isGRegWR() &&
                       (blockstatus == TheISA::Normal)));

        return (status_valid && (instructions[addr & lowerMask]->machInst == mach_inst));
    }

    /// Returns the instruction object. decoded should be called first
    /// to check if the instruction is valid.
    /// @param addr The address of the instruction.
    /// @retval A pointer to the corresponding StaticInst object.
    EDGEStaticInstPtr
    getInst(Addr addr)
    {
        return instructions[addr & lowerMask];
    }

    /// Inserts a pointer to a StaticInst object into the list of decoded
    /// instructions on the page.
    /// @param addr The address of the instruction.
    /// @param si A pointer to the corresponding StaticInst object.
    void
    insert(Addr addr, EDGEStaticInstPtr &si)
    {
        instructions[addr & lowerMask] = si;
        valid[addr & lowerMask] = true;
    }
};

inline EDGEStaticInstPtr
EDGEStaticInst::decode(EDGEStaticInst::ExtMachInst mach_inst, Addr addr, TheISA::BlockStatus blockstatus)
{
#ifdef DECODE_CACHE_HASH_STATS
    // Simple stats on decode hash_map.  Turns out the default
    // hash function is as good as anything I could come up with.
    const int dump_every_n = 10000000;
    static int decodes_til_dump = dump_every_n;

    if (--decodes_til_dump == 0) {
        dumpDecodeCacheStats();
        decodes_til_dump = dump_every_n;
    }
#endif

    Addr page_addr = addr & ~(TheISA::PageBytes - 1);

    // checks recently decoded addresses
    if (recentDecodes[0].decodePage &&
        page_addr == recentDecodes[0].page_addr) {
        if (recentDecodes[0].decodePage->decoded(mach_inst, addr, blockstatus))
            return recentDecodes[0].decodePage->getInst(addr);

        return searchCache(mach_inst, addr, recentDecodes[0].decodePage, blockstatus);
    }

    if (recentDecodes[1].decodePage &&
        page_addr == recentDecodes[1].page_addr) {
        if (recentDecodes[1].decodePage->decoded(mach_inst, addr, blockstatus))
            return recentDecodes[1].decodePage->getInst(addr);

        return searchCache(mach_inst, addr, recentDecodes[1].decodePage, blockstatus);
    }

    // searches the page containing the address to decode
    AddrDecodeCache::iterator iter = addrDecodeCache.find(page_addr);
    if (iter != addrDecodeCache.end()) {
        updateCache(page_addr, iter->second);
        if (iter->second->decoded(mach_inst, addr, blockstatus))
            return iter->second->getInst(addr);

        return searchCache(mach_inst, addr, iter->second, blockstatus);
    }

    // creates a new object for a page of decoded instructions
    EDGEAddrDecodePage *decodePage = new EDGEAddrDecodePage;
    addrDecodeCache[page_addr] = decodePage;
    updateCache(page_addr, decodePage);
    return searchCache(mach_inst, addr, decodePage, blockstatus);
}

inline EDGEStaticInstPtr
EDGEStaticInst::searchCache(ExtMachInst mach_inst, Addr addr,
                        EDGEAddrDecodePage *decodePage, TheISA::BlockStatus blockstatus)
{
    DecodeCache::iterator iter = decodeCache.find(mach_inst);

    if (iter != decodeCache.end()) {
        // We can only get reg-write/read inst in Head status and
        // non-reg-write/read inst in Normal status
        if ( (iter->second->isGRegWR() && blockstatus == TheISA::Head )
            || (!iter->second->isGRegWR() && !iter->second->isRead()
            && !iter->second->isWrite()&& blockstatus == TheISA::Normal)
            || (iter->second->isWrite() && blockstatus == TheISA::HeaderWrite)
            || (iter->second->isRead() && blockstatus == TheISA::HeaderRead)) {

            decodePage->insert(addr, iter->second);
            return iter->second;
        }
    }

    EDGEStaticInstPtr si = TheISA::decodeInst(mach_inst, blockstatus);
    decodePage->insert(addr, si);
    decodeCache[mach_inst] = si;
    return si;
}

#endif // __EDGECPU_STATIC_INST_HH__
